﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Objects;
using System.Linq;
using VO.Entities;

namespace VO.Business.Controllers
{
    public static class ClubsController
    {
        public static List<Club> GetClubs()
        {
            using (ModelVOContainer ctx = new ModelVOContainer())
            {
                return ctx.Clubs.ToList();
            }
        }

        public static Club GetClub(Guid id)
        {
            using (ModelVOContainer ctx = new ModelVOContainer())
            {
                return ctx.Clubs.SingleOrDefault(p=> p.Id == id);
            }
        }

        public static bool SaveClub(Club club, bool  isnew)
        {
            using (ModelVOContainer ctx = new ModelVOContainer())
            {
                club.LastEditDate = DateTime.Now;

                try
                {
                    ctx.Clubs.Attach(club);
                    if (isnew)
                    {
                        club.CreatedDate = DateTime.Now;
                    }
                    ctx.ObjectStateManager.ChangeObjectState(club, isnew ? EntityState.Added : EntityState.Modified);

                    return ctx.SaveChanges() > 0;
                }
                catch (OptimisticConcurrencyException exOpt)
                {
                    ctx.Refresh(RefreshMode.ClientWins, club);
                    return ctx.SaveChanges() > 0;
                }
                catch (Exception)
                {
                    throw;
                }
            }
        }
    }
}
